package cn.stylefeng.guns.modular.robot.cmd.impl;

import cn.stylefeng.guns.modular.robot.cmd.abs.AbstractCmd;
import cn.stylefeng.guns.modular.robot.entity.Group;
import cn.stylefeng.guns.modular.robot.entity.GroupRelationship;
import cn.stylefeng.guns.modular.robot.entity.LowerMessage;
import cn.stylefeng.guns.modular.robot.entity.vo.resp.TgFileResp;
import cn.stylefeng.guns.modular.robot.service.CdInfoService;
import cn.stylefeng.guns.modular.robot.service.GroupRelationshipService;
import cn.stylefeng.guns.modular.robot.service.GroupService;
import cn.stylefeng.guns.modular.robot.service.LowerMessageService;
import cn.stylefeng.guns.modular.robot.utils.RobotUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.client.RestTemplate;
import org.telegram.telegrambots.bots.TelegramLongPollingBot;
import org.telegram.telegrambots.meta.api.objects.Message;
import org.telegram.telegrambots.meta.api.objects.Update;
import org.telegram.telegrambots.meta.exceptions.TelegramApiException;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.*;

@Slf4j
@Service
@Transactional
public class CmdPhoto extends AbstractCmd {
    @Resource
    private RestTemplate restTemplate;
    @Resource
    private GroupRelationshipService groupRelationshipService;
    @Resource
    private LowerMessageService lowerMessageService;
    @Resource
    private GroupService groupService;
    @Resource
    private CdInfoService cdInfoService;

    @Override
    public void exec(Update update, TelegramLongPollingBot bot) {
        Long chatId = update.getMessage().getChatId();
        String cmd = update.getMessage().getCaption();
        if (StringUtils.isBlank(cmd) || (!cmd.toUpperCase(Locale.ROOT).startsWith("/CD") && !cmd.toUpperCase(Locale.ROOT).equals("ZF"))) {
            return;
        }
        log.info("群消息发送：群名称：" + update.getMessage().getChat().getTitle() + "，发送人：" + update.getMessage().getFrom().getUserName() + "，群图片消息内容:" + update.getMessage().getCaption()+"，群图片id："+ update.getMessage().getPhoto().get(update.getMessage().getPhoto().size()-1).getFileId());
        //是否下游群
        List<GroupRelationship> groupRelationships = groupRelationshipService.lambdaQuery()
                .eq(GroupRelationship::getSendGroupId, chatId)
                .list();
        if (CollectionUtils.isEmpty(groupRelationships)) {
            return;
        }
        //是否上下游群都开启账单
        GroupRelationship groupRelationship = groupRelationships.get(0);
        if (!verificationSendStatus(groupRelationship)) {
            return;
        }
        //下载文件，转发上游群，记录
        TgFileResp.Result result=null;
        try {
            String caption = handleText(update,groupRelationship.getReceiveGroupId());
            result = RobotUtils.downloadFileAsStream(restTemplate, update, bot);
            if (Objects.isNull(result)) {
                return;
            }
            Message message = RobotUtils.sendPhoto(groupRelationship.getReceiveGroupId(), caption, result.getInputStream(), result.getFile_path(), bot);
            LowerMessage lowerMessage = getLowerMessage(update, message);
            lowerMessageService.save(lowerMessage);
            Group receiveGroup = groupService.getGroupByTgGroupId(groupRelationship.getReceiveGroupId());
            RobotUtils.sendText(chatId, "记账图已同步至上游群：" + receiveGroup.getName(), update.getMessage().getMessageId(), bot);
        } catch (TelegramApiException e) {
            log.error("注意图片转发失败：TelegramApiException：" + e.getMessage());
        }finally {
            if(result!=null && result.getInputStream()!=null){
                try {
                    result.getInputStream().close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }

    private String handleText(Update update, Long receiveGroupId) {
        String text = update.getMessage().getCaption();
        if (text.toUpperCase(Locale.ROOT).equals("ZF")) {
            return null;
        }
        Group group = groupService.getGroupByTgGroupId(update.getMessage().getChatId());
        String replace = text.replace("/CD\n", "").replace("/cd\n", "").replace("zf", "").replace("ZF", "");
        StringBuilder sb = new StringBuilder();
        sb.append(replace + "\n");
        sb.append("--（来自").append(group.getName()).append("）\n");
        try {
            cdInfoService.createCdInfo(replace,receiveGroupId);
        }catch (Exception e){
            log.error("查单失败L：",e);
        }
//        sb.append("图片编号（#)\n");
//        sb.append("查单编号（#)\n");
        return sb.toString();
    }

    private boolean verificationSendStatus(GroupRelationship groupRelationship) {
        Long sendGroupId = groupRelationship.getSendGroupId();
        Long receiveGroupId = groupRelationship.getReceiveGroupId();
        List<Group> groups = groupService.lambdaQuery()
                .in(Group::getTgGroupId, Arrays.asList(sendGroupId, receiveGroupId))
                .list();
        for (Group group : groups) {
            if (!Boolean.TRUE.equals(group.getBatchStatus())) {
                return false;
            }
        }
        return true;
    }

    private static LowerMessage getLowerMessage(Update update, Message message) {
        LowerMessage lowerMessage = new LowerMessage();
        //上游群新消息id
        lowerMessage.setMessageId(message.getMessageId());
        lowerMessage.setUpGroupId(message.getChatId());
        //下游群信息
        lowerMessage.setLowerMessageId(update.getMessage().getMessageId());
        lowerMessage.setGroupId(update.getMessage().getChatId());
        lowerMessage.setGroupName(update.getMessage().getChat().getTitle());
        lowerMessage.setCustomId(update.getMessage().getFrom().getId());
        lowerMessage.setCustomName(update.getMessage().getFrom().getUserName());
        lowerMessage.setFileId(message.getPhoto().get(message.getPhoto().size() - 1).getFileId());
        lowerMessage.setCreateBy(update.getMessage().getFrom().getUserName());
        lowerMessage.setCreateTime(new Date());
        return lowerMessage;
    }

    @Override
    public String getCmdName() {
        return "/PHOTO";
    }

    @Override
    public String getDescribe() {
        return "ZF                              转发图片到上游群\n";
    }
}




